﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Threading;

namespace Eugenhome.Atrium.Rss.Web
{
    /// <summary>
    /// 
    /// </summary>
    public partial class RssView : System.Web.UI.Page
    {
        /// <summary></summary>
        private RssSourceCollection _rsc
        {
            get
            {
                if (Session["_rsc"] == null)
                {
                    //string proxyAddress = WebConfigurationManager.AppSettings[DAO.WEBCONFIG_HOSTINGPROXY_KEY] != null ? WebConfigurationManager.AppSettings[DAO.WEBCONFIG_HOSTINGPROXY_KEY] : "";

                    Session["_rsc"] = RssSourceCollection.Load(Server.MapPath("rss.xml"));

                    List<RssSource> sourceItemList = ((RssSourceCollection)Session["_rsc"]).RssSources;
                    List<string> errors = new List<string>();

                    foreach(var sourceItem in ((RssSourceCollection)Session["_rsc"]).RssSources)
                    {
                        errors.AddRange(sourceItem.DataBind(false, true).Errors);
                    }

                    imgConnected.ToolTip = "";
                    errors.ForEach(item => imgConnected.ToolTip += item + "; ");

                    bool connected = sourceItemList.Count.Equals(0) ? true : sourceItemList[0].Items.Responsed;
                    imgConnected.ImageUrl = connected ? DAO.IMAGE_CONNECTED : DAO.IMAGE_DISCONNECTED;
                }

                return (RssSourceCollection)Session["_rsc"];
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UpdateSourceList(true);

                SearchNextActivTab(null);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void Reload()
        {
            Session["_rsc"] = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reload"></param>
        private void UpdateSourceList(bool reload)
        {
            if (reload) Reload();

            string savedSelectedLabel = cbLabels.SelectedValue;

            List<RssSourceItem> sourceItemList = _rsc.RssSources.Select(item => new RssSourceItem(item)).ToList();

            if (!sourceItemList.Count.Equals(0))
            {
                cbLabels.DataSource = sourceItemList;
                cbLabels.DataTextField = "DisplayName";
                cbLabels.DataValueField = "Name";
                cbLabels.DataBind();
                cbLabels.SelectedValue = savedSelectedLabel;

                cbLabels_SelectedIndexChanged(null, null);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cbLabels_SelectedIndexChanged(object sender, EventArgs e)
        {
            _rsc.SetSelectedLabel(cbLabels.SelectedValue);

            repRssItems.DataSource = _rsc.RssSources.Where(item => item.Name.Equals(_rsc.SelectedLabel)).FirstOrDefault().Items.Cast<Rss>().Select(item => new RssItem(item)).ToList();
            repRssItems.DataBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCheckAll_Click(object sender, ImageClickEventArgs e)
        {
            RssSource selectedRssSource = _rsc.RssSources.Where(item => item.Name.Equals(_rsc.SelectedLabel)).FirstOrDefault();

            if (selectedRssSource != null && !selectedRssSource.Items.Count.Equals(0))
            {
                selectedRssSource.SetReaded(selectedRssSource.Items.Cast<Rss>().Max(item => item.PubDate));
            }

            SearchNextActivTab(selectedRssSource);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnShowAll_Click(object sender, ImageClickEventArgs e)
        {
            RssSource selectedRssSource = _rsc.RssSources.Where(item => item.Name.Equals(_rsc.SelectedLabel)).FirstOrDefault();

            if (selectedRssSource != null)
            {
                selectedRssSource.LastReaded = DateTime.MinValue;


                selectedRssSource.DataBind(false, false);

                UpdateSourceList(false);

            }

            SearchNextActivTab(selectedRssSource);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="selectedRssSource"></param>
        private void SearchNextActivTab(RssSource selectedRssSource)
        {
            List<RssSource> sourses = _rsc.RssSources;

            if (selectedRssSource != null)
            {
                int index = _rsc.RssSources.IndexOf(selectedRssSource);

                sourses = _rsc.RssSources.GetRange(index, _rsc.RssSources.Count - index);
                sourses.AddRange(_rsc.RssSources.GetRange(0, index));
            }

            RssSource nextSource = sourses.Find(item => !item.Items.Count.Equals(0));

            if (nextSource != null)
            {
                cbLabels.SelectedValue = nextSource.Name;
                UpdateSourceList(false);
            }
            else if (selectedRssSource != null)
            {
                UpdateSourceList(true);
                SearchNextActivTab(null);
            }
        }


    }
}